// Copyright (c) 2025, hzmes and contributors
// For license information, please see license.txt

frappe.ui.form.on("HSF Release Task", {
	refresh(frm) {
                // 提示
                if (frm.is_new()) {frm.set_intro('先保存表头成功,再根据产品编码获取产品BOM', 'green');}
                // 同步BOM
                if (!frm.is_new() && frm.doc.docstatus == 0) {
                        frm.add_custom_button('BOM正查', () => {
                            frappe.call('srm_hsf.hazardous_substances_free.doctype.hsf_release_task.hsf_release_task.sync_bom', {
                                docname: frm.doc.name,
                                org: frm.doc.user_org,
                                material_number: frm.doc.product_code,
                                bomverson: frm.doc.bomverson
                            }).then(r => {
                                console.log(r.message);
                                r.message.forEach(item => {let row = frm.add_child('items', {item_code: item.MATERIAL});})
                                frm.refresh_field('items');
                                frm.save();
                            })
                        })
                }
                // 获取供应商
                if (!frm.is_new() && frm.doc.docstatus == 0) {
                        frm.add_custom_button('获取供应商', () => {
                                frm.call({
                                        method: "get_supplier",
                                        doc: frm.doc,
                                        callback: function (r) {
                                                refresh_field("items");
                                                console.log(r.message);
                                                frappe.msgprint(`更新了${r.message}行记录`)
                                        },
                                });
                        })
                }
                // 同步发布状态
                if (!frm.is_new() && frm.doc.docstatus == 0) {
                        frm.add_custom_button('同步发布状态', () => {
                                frm.call({
                                        method: "validate_release_status",
                                        doc: frm.doc,
                                        callback: function (r) {
                                                refresh_field("items");
                                                console.log(r.message);
                                                frappe.msgprint(`更新了${r.message}行记录`)
                                        },
                                });
                        })
                }
	},
});

